package com.qgs.rabbitmqapi.consumer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/24 10:54
 * @Version 1.0
 */
public class MyHeaderConsumer extends DefaultConsumer {


    Logger logger = LoggerFactory.getLogger(com.qgs.rabbitmqapi.consumer.MyHeaderConsumer.class);

    private Channel channel;

    public MyHeaderConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        super.handleDelivery(consumerTag, envelope, properties, body);
        logger.info("-------------consumer message-----------------");
        try {
            Thread.sleep(2000);
        }catch (Exception e){

        }
        logger.info("body:"+new String(body,"UTF-8"));
        Integer c = (Integer)properties.getHeaders().get("num");
        logger.info("header-num-content:"+c);

        //logger.info("header-num-content:",(Integer)properties.getHeaders().get("num")); 不是这么写的。
        if(c == 0){
            // 如果num ==0 那么把这条消息距居然并且让它重回队列。
            // multiple是 是否支持批量处理 ，requeue 是 是否重回队列。
            channel.basicNack(envelope.getDeliveryTag(),false,true);
        }else {
            //签收消息（任务队列的关键。）
            channel.basicAck(envelope.getDeliveryTag(),false);
        }

        //channel.basicAck(envelope.getDeliveryTag(),false);
    }
}
